<template>
  <div class="menu-management">
    <!-- 左侧菜单树 -->
    <div class="menu-tree-container">
      <h3>菜单树</h3>
      <el-tree
        ref="menuTreeRef"
        :data="menuTreeData"
        node-key="id"
        draggable
        :allow-drop="allowDrop"
        @node-drop="handleNodeDrop"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span class="menu-type">({{ data.type === 'menu' ? '菜单' : '按钮' }})</span>
            <span class="tree-actions">
              <el-button
                v-if="data.type === 'menu'"
                link
                type="primary"
                size="small"
                @click.stop="handleAddChild(node, data)"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click.stop="handleRemove(node, data)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 右侧区域 -->
    <div class="menu-content">
      <!-- 右侧上方功能区 -->
      <div class="menu-operation">
        <h3>菜单操作</h3>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="菜单名称">
            <el-input v-model="searchForm.name" placeholder="请输入菜单名称" clearable />
          </el-form-item>
          <el-form-item label="菜单类型">
            <el-select v-model="searchForm.type" placeholder="请选择菜单类型" clearable>
              <el-option label="菜单" value="menu" />
              <el-option label="按钮" value="button" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">新增菜单</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 右侧下方表格 -->
      <div class="menu-table">
        <h3>菜单列表</h3>
        <el-table :data="filteredTableData" border style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="菜单名称" width="180" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.type === 'menu' ? 'primary' : 'success'">
                {{ scope.row.type === 'menu' ? '菜单' : '按钮' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="路由路径" />
          <el-table-column prop="permission" label="权限标识" />
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 菜单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑菜单' : '新增菜单'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="button">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.type === 'menu'" label="路由路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item v-if="form.type === 'button'" label="权限标识" prop="permission">
          <el-input v-model="form.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

console.log('当前 submitForm 是否存在：', typeof submitForm)
// 菜单树数据
const menuTreeData = ref([
  {
    id: 1,
    label: '系统管理',
    type: 'menu',
    children: [
      {
        id: 2,
        label: '用户管理',
        type: 'menu',
        children: [
          { id: 3, label: '查看用户', type: 'button' },
          { id: 4, label: '新增用户', type: 'button' },
          { id: 5, label: '编辑用户', type: 'button' },
          { id: 6, label: '删除用户', type: 'button' }
        ]
      },
      {
        id: 7,
        label: '角色管理',
        type: 'menu',
        children: [
          { id: 8, label: '查看角色', type: 'button' },
          { id: 9, label: '新增角色', type: 'button' },
          { id: 10, label: '编辑角色', type: 'button' },
          { id: 11, label: '删除角色', type: 'button' }
        ]
      }
    ]
  },
  {
    id: 12,
    label: '内容管理',
    type: 'menu',
    children: [
      { id: 13, label: '文章管理', type: 'menu' },
      { id: 14, label: '分类管理', type: 'menu' }
    ]
  }
])

// 右侧表格数据(从树结构转换而来)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  type: ''
})

// 表单对话框相关
const dialogVisible = ref(false)
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: 'menu',
  path: '',
  permission: '',
  sort: 0
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  permission: [{ required: true, message: '请输入权限标识', trigger: 'blur' }]
}

// 菜单树引用
const menuTreeRef = ref(null)
const currentNode = ref(null)
const handleNodeClick = (data, node) => {
  currentNode.value = node
}
// 过滤后的表格数据(根据搜索条件)
const filteredTableData = computed(() => {
  return tableData.value.filter(item => {
    const nameMatch = !searchForm.name || item.name.includes(searchForm.name)
    const typeMatch = !searchForm.type || item.type === searchForm.type
    return nameMatch && typeMatch
  })
})

// 将树结构转换为表格数据
const convertTreeToTable = (treeData) => {
  let result = []
  treeData.forEach(node => {
    // 添加当前节点
    result.push({
      id: node.id,
      name: node.label,
      type: node.type,
      path: node.path || '',
      permission: node.permission || '',
      sort: node.sort || 0
    })
    
    // 递归添加子节点
    if (node.children && node.children.length > 0) {
      result = result.concat(convertTreeToTable(node.children))
    }
  })
  return result
}

// 初始化表格数据
const initTableData = () => {
  tableData.value = convertTreeToTable(menuTreeData.value)
}

// 允许拖拽放置的条件
const allowDrop = (draggingNode, dropNode, type) => {
  // 只允许在同级节点间拖拽
  if (type === 'inner') {
    return false
  }
  return true
}

// 处理节点拖拽完成事件
const handleNodeDrop = (draggingNode, dropNode, dropType) => {
  // 重新构建树结构(因为拖拽后节点位置变化)
  // 这里简单处理，实际项目中可能需要调用API保存排序
  initTableData()
  ElMessage.success('菜单顺序已更新')
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑已通过computed属性实现
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.type = ''
}

// 新增菜单
const handleAdd = () => {
  form.id = ''
  form.name = ''
  form.type = 'menu'
  form.path = ''
  form.permission = ''
  form.sort = 0
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row) => {
  // 在树结构中查找对应的节点
  const findNode = (nodes, id) => {
    for (const node of nodes) {
      if (node.id === id) {
        return node
      }
      if (node.children && node.children.length > 0) {
        const found = findNode(node.children, id)
        if (found) return found
      }
    }
    return null
  }
  
  const node = findNode(menuTreeData.value, row.id)
  if (node) {
    form.id = node.id
    form.name = node.label
    form.type = node.type
    form.path = node.path || ''
    form.permission = node.permission || ''
    form.sort = node.sort || 0
    dialogVisible.value = true
  }
}

// 删除菜单
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 在树结构中查找并删除节点
    const deleteNode = (nodes, id) => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === id) {
          nodes.splice(i, 1)
          return true
        }
        if (nodes[i].children && nodes[i].children.length > 0) {
          if (deleteNode(nodes[i].children, id)) {
            return true
          }
        }
      }
      return false
    }
    
    deleteNode(menuTreeData.value, row.id)
    initTableData()
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 提交表单
// const submitForm = () => {
//   if (!formRef.value) return
  
//   formRef.value.validate((valid) => {
//     if (valid) {
//       if (form.id) {
//         // 编辑现有菜单
//         const updateNode = (nodes, id, newData) => {
//           for (const node of nodes) {
//             if (node.id === id) {
//               Object.assign(node, { label: newData.name, type: newData.type, path: newData.path, permission: newData.permission, sort: newData.sort })
//               return true
//             }
//             if (node.children && node.children.length > 0) {
//               if (updateNode(node.children, id, newData)) {
//                 return true
//               }
//             }
//           }
//           return false
//         }
        
//         updateNode(menuTreeData.value, form.id, form)
//       } else {
//         // 新增菜单(简化处理，实际项目中需要确定父节点)
//         const newId = Math.max(...menuTreeData.value.flatMap(node => [node.id, ...(node.children ? node.children.map(c => c.id) : [])]), 0) + 1
//         const newNode = {
//           id: newId,
//           label: form.name,
//           type: form.type,
//           path: form.path,
//           permission: form.permission,
//           sort: form.sort,
//           children: []
//         }
        
//         // 简单处理，新增到根节点
//         menuTreeData.value.push(newNode)
//       }
      
//       initTableData()
//       dialogVisible.value = false
//       ElMessage.success(form.id ? '更新成功' : '新增成功')
//     }
//   })
// }
const handleAddChild = (node, data) => {
  form.id = '' // 清空ID表示新增
  form.name = '新菜单'
  form.type = 'menu' // 默认添加菜单类型
  form.path = ''
  form.permission = ''
  form.sort = 0
  
  // 保存当前父节点信息，用于后续添加子节点
  currentNode.value = node
  
  dialogVisible.value = true
}

// 新增方法: 移除菜单
const handleRemove = (node, data) => {
  if (data.children && data.children.length > 0) {
    ElMessageBox.warning('该菜单下有子菜单，不能直接删除！')
    return
  }
  
  ElMessageBox.confirm('确认删除该菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 从树中删除节点
    if (node.parent) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(item => item.id === data.id)
      if (index !== -1) {
        children.splice(index, 1)
      }
    } else {
      // 如果是根节点
      const index = menuTreeData.value.findIndex(item => item.id === data.id)
      if (index !== -1) {
        menuTreeData.value.splice(index, 1)
      }
    }
    
    initTableData()
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 修改后的提交表单方法(支持添加子菜单)
// const submitForm = () => {
//   if (!formRef.value) return
  
//   formRef.value.validate((valid) => {
//     if (valid) {
//       if (form.id) {
//         // 编辑现有菜单(保持不变)
//         const updateNode = (nodes, id, newData) => {
//           for (const node of nodes) {
//             if (node.id === id) {
//               Object.assign(node, { label: newData.name, type: newData.type, path: newData.path, permission: newData.permission, sort: newData.sort })
//               return true
//             }
//             if (node.children && node.children.length > 0) {
//               if (updateNode(node.children, id, newData)) {
//                 return true
//               }
//             }
//           }
//           // dialogVisible.value = false
//           return false
//         }
        
//         updateNode(menuTreeData.value, form.id, form)
//       } else {
//         // 新增菜单 - 判断是否是子菜单
//         if (currentNode.value) {
//           // 添加子菜单
//           const newId = Math.max(
//             ...menuTreeData.value.flatMap(node => [node.id, ...(node.children ? node.children.map(c => c.id) : [])]),
//             0
//           ) + 1
          
//           const newNode = {
//             id: newId,
//             label: form.name,
//             type: form.type,
//             path: form.path,
//             permission: form.permission,
//             sort: form.sort,
//             children: []
//           }
          
//           // 添加到当前选中节点的children中
//           if (!currentNode.value.data.children) {
//             currentNode.value.data.children = []
//           }
//           currentNode.value.data.children.push(newNode)
//         } else {
//           // 添加根节点菜单(保持不变)
//           const newId = Math.max(
//             ...menuTreeData.value.flatMap(node => [node.id, ...(node.children ? node.children.map(c => c.id) : [])]),
//             0
//           ) + 1
//           const newNode = {
//             id: newId,
//             label: form.name,
//             type: form.type,
//             path: form.path,
//             permission: form.permission,
//             sort: form.sort,
//             children: []
//           }
//           menuTreeData.value.push(newNode)
//         }
//       }
      
//       initTableData()
//       dialogVisible.value = false
//       ElMessage.success(form.id ? '更新成功' : '新增成功')
//       console.log(currentNode.value);
      
//     }
//   })
// }

const submitForm = async () => {
  console.log('submitForm 被调用了')
  try {
    await formRef.value.validate()
    // 模拟或真实的 API 调用
    await saveMenuAPI(form)

    ElMessage.success(form.id ? '更新成功' : '新增成功')
    dialogVisible.value = false
    initTableData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initTableData()
})
</script>

<style scoped>
.menu-management {
  display: flex;
  height: 100%;
  gap: 20px;
}

.menu-tree-container {
  width: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  overflow: auto;
}

.menu-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.menu-operation {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.menu-table {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  overflow: auto;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.menu-type {
  font-size: 12px;
  color: #909399;
}

.search-form {
  margin-top: 15px;
}
</style>